/*
 * @Author: 李一番 
 * @Date: 2021-12-27 16:28:58 
 * @Last Modified by: 李一番
 * @Last Modified time: 2021-12-29 17:09:53
 */
import { start, done, configure } from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'
import { isObject } from '@vue/shared'

import { getCookie, hasMenuPermission } from '@/utils/auth'
import { RouteLocationNormalized } from 'vue-router'
import store from '@/store'

const whiteList = ['/login']
router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next) => {
  start()
  
  if (getCookie('token')) {
    if (to.path === '/login') {
      next({ path: '/' })
      done()
    } else {
      try {
        // 获取存储在cookie里面的菜单权限和按钮权限
        const menu = store.state.permission.menuPermission
        if (JSON.stringify(menu) === '{}') {
          const menuPermission = await store.dispatch('permission/getMenuPer')
          hasMenuPermission(menuPermission, to) ? next() : next('/error/401');
        } else {
          hasMenuPermission(menu, to) ? next() : next('/error/401');
        }
      } catch (error) {
        next('/error/401')
        console.log('路由错误:', error)
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next({ path: '/login' })
      done()
    }
  }
})

router.afterEach(() => {
  done()
})
